# -*- coding: UTF-8 -*-
import urllib
import urllib2
import re
import thread
import time
import sys
import codecs
import random
import socket

reload(sys)
sys.setdefaultencoding('utf-8')
socket.setdefaulttimeout(30)


#糗事百科爬虫类
class DBTS:

    #初始化方法，定义一些变量
    def __init__(self):
        self.pageIndex = 0
        self.user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'
        #初始化headers
        self.headers = { 'User-Agent' : self.user_agent }
        #存放段子的变量，每一个元素是每一页的段子们
        self.stories = []
        #存放书本名,书名，id，地址
        self.mainBooks = []
        #存放程序是否继续运行的变量
        self.enable = False
        self.proxy()
    #设置代理
    def proxy(self):
        f = open("E:/toOrigin/myNote/pythonSpider/proxy/data.txt")
        lines = f.readlines()
        i = random.randint(1,36)
        ip = lines[i].strip("\n").split("\t")
        proxy_host = "https://"+ip[0]+":"+ip[1]
        print u"代理"+proxy_host+u"为您工作"
        proxy_handler=urllib2.ProxyHandler({"https":proxy_host})
        opener=urllib2.build_opener(proxy_handler)
        urllib2.install_opener(opener)
        f.close()
    def testIsBank(self,content):
        isBank = re.search("https://www.douban.com/accounts/login?redir=https",content)
        if isBank:
            print u"反爬虫：被禁，正在寻找下一个代理"
            self.proxy()
    #传入某一页的索引获得页面html,一页20本书
    def getMainBook(self,pageIndex):
        try:
            print u"正在获取第"+str(pageIndex)+"页"
            url = 'https://book.douban.com/tag/%E7%A7%91%E5%B9%BB?start='+str((pageIndex-1)*20)+'&type=T'
            #构建请求的request
            request = urllib2.Request(url,headers = self.headers);
            #利用urlopen获取页面
            response = urllib2.urlopen(request,timeout=10)
            #页面转码
            content = response.read().decode('utf-8')

            pattern = re.compile('<div.*?class="info.*?>.*?<a.*?href="(.*?)".*?title="(.*?)".*?subject_id:\'(.*?)\'.*?</a>',re.S)
            items = re.findall(pattern,content)

            #遍历正则表达式匹配的信息
            for item in items:
                    self.mainBooks.append([item[0].strip(),item[1].strip(),item[2].strip()])
            return

            return content
        except urllib2.URLError, e:
            if hasattr(e,"reason"):
                print u"连接豆瓣失败，错误原因：",e.reason
                self.proxy()
                return
    #分解主页面，获取爬虫任务url
    def getMainTask(self):
        print len(self.mainBooks)
        while len(self.mainBooks)>0:
                #从全局list中获取一个书名
                currentBook = self.mainBooks[0]
                #保存到mysql-------------------------
                try:
                    print u"保存进数据库"+currentBook[1]
                    #将全局list中第一个元素删除，因为已经取出
                    del self.mainBooks[0]
                    url = currentBook[0]
                    print url;
                    #下一个任务
                    self.getBookComment(currentBook[1],url,0)

                except UnicodeEncodeError, e:
                    print u"编码错误，跳过"
                    del self.mainBooks[0]
                #return url
        self.pageIndex += 1
        self.getMainBook(self.pageIndex)
        self.getMainTask();

    #获取书本的评论
    def getBookComment(self,bookName,bookUrl,cIndex):
        try:
            print u"正在获取"+bookName+"的评论"
            print u"第"+str(cIndex+1)+"页"
            #if cIndex == 6:
            #    self.getBookComment(bookName,bookUrl,cIndex+1)
            #    return
            url = bookUrl+'collections?start='+str(cIndex*20)
            #构建请求的request
            request = urllib2.Request(url,headers = self.headers);
            #利用urlopen获取页面
            response = urllib2.urlopen(request,timeout=30)
            #页面转码
            content = response.read().decode('utf-8')
            #print content
            print u"请求已完成"
            testIsBank(content)
            patternItem = re.compile('collections_tab.*?paginator',re.S)
            code = re.findall(patternItem,content)
            pattern = re.compile('<td.*?valign="top".*?<a.*?<span.*?class.*?>(.*?)</span>.*?</a>.*?<p.*?class="pl".*?>.*?<span.*?class="allstar(.*?)".*?</td>',re.S)
            items = re.findall(pattern,str(code))
            print u"正则已完成"

            #遍历正则表达式匹配的信息
            for item in items:
                try:
                    #if item[1] !="" :
                    a=open('E:/data.txt', 'a')
                    a.write(bookName+"\t"+item[0].decode("unicode-escape")+"\t"+item[1]+"\n")
                    a.close()
                    print u"用户 "+item[0].decode("unicode-escape")+u"评分 "+item[1]
                except UnicodeEncodeError, e:
                    print u"用户名编码有误，跳过"
            if len(items) == 0:
                print bookName+u"的评论已全部加载完毕！！！"
                return
            else:
                self.getBookComment(bookName,bookUrl,cIndex+1)

            return
        except urllib2.URLError, e:
            if hasattr(e,"reason"):
                print u"连接豆瓣失败，错误原因：",e.reason
                return


    def getPage(self,pageIndex):
        try:
            url = 'https://www.qiushibaike.com/8hr/page/' + str(pageIndex)
            #构建请求的request
            request = urllib2.Request(url,headers = self.headers)
            #利用urlopen获取页面代码
            response = urllib2.urlopen(request,timeout=3)
            #将页面转化为UTF-8编码
            pageCode = response.read().decode('utf-8')
            return pageCode

        except urllib2.URLError, e:
            if hasattr(e,"reason"):
                print u"连接糗事百科失败,错误原因",e.reason
                return None

    #传入某一页代码，返回本页不带图片的段子列表
    def getPageItems(self,pageIndex):
        pageCode = self.getPage(pageIndex)
        if not pageCode:
            print "页面加载失败...."
            return None
        pattern = re.compile('<div.*?class="author.*?>.*?<a.*?</a>.*?<a.*?>.*?<h2>(.*?)</h2>.*?</a>.*?</div>.*?</div>.*?<a.*?>.*?<div.*?class'+
                         '="content".*?>(.*?)</div>.*?</a>(.*?)<div class="stats.*?class="number">(.*?)</i>',re.S)
        items = re.findall(pattern,pageCode)
        #用来存储每页的段子们
        pageStories = []
        #遍历正则表达式匹配的信息
        for item in items:
            #是否含有图片
            haveImg = re.search("img",item[2])
            #如果不含有图片，把它加入list中
            if not haveImg:
                #item[0]是一个段子的发布者，item[1]是内容，item[3]是点赞数
                pageStories.append([item[0].strip(),item[1].strip(),item[3].strip()])
        return pageStories

    #加载并提取页面的内容，加入到列表中
    def loadPage(self):
        #如果当前未看的页数少于2页，则加载新一页
        if self.enable == True:
            if len(self.stories) < 2:
                #获取新一页
                pageStories = self.getPageItems(self.pageIndex)
                #将该页的段子存放到全局list中
                if pageStories:
                    self.stories.append(pageStories)
                    #获取完之后页码索引加一，表示下次读取下一页
                    self.pageIndex += 1

    #调用该方法，每次敲回车打印输出一个段子
    def getOneStory(self,pageStories,page):
        #遍历一页的段子
        for story in pageStories:
            #等待用户输入
            input = raw_input()
            #每当输入回车一次，判断一下是否要加载新页面
            self.loadPage()
            #如果输入Q则程序结束
            if input == "Q":
                self.enable = False
                return
            try:
                print u"第%d页\t发布人:%s\n内容：%s\n赞:%s\n" %(page,story[0],story[1],story[2])
            except UnicodeEncodeError, e:
                print "--------------------------------------------------------字符集错误---------------------------------------------------------------------------------------"
                return

    #开始方法
    def start(self):
        print u"正在读取糗事百科,按回车查看新段子，Q退出"
        #使变量为True，程序可以正常运行
        self.enable = True
        #先加载一页内容
        self.loadPage()
        #局部变量，控制当前读到了第几页
        nowPage = 0
        while self.enable:
            if len(self.stories)>0:
                #从全局list中获取一页的段子
                pageStories = self.stories[0]
                #当前读到的页数加一
                nowPage += 1
                #将全局list中第一个元素删除，因为已经取出
                del self.stories[0]
                #输出该页的段子
                self.getOneStory(pageStories,nowPage)

spider = DBTS()
#content =  spider.getMainBook(1)
spider.getMainTask()
#print content
